<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Model;
use think\Db;
use Exception;
use app\api\controller\kuyou\applet\Goods as Goodss;
class Sales extends Model
{

    // 表名
    protected $name = 'kuyou_goods_sales';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit,$sort_field,$sort_type){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->page($page,$limit)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,purchase_order_id,returns_order_id,number,all_money,preferential_money,real_money,tax_money,money_tax_price,preparation_id,examine_id,check_status,examine_status,note,print_num,pay_status,pay_money")->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->order($sort_field,$sort_type)->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,purchase_order_id,returns_order_id,number,all_money,preferential_money,real_money,tax_money,money_tax_price,preparation_id,examine_id,check_status,examine_status,note,print_num,pay_status,pay_money")->select())->toArray();
        }

        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['customers'] = (new Customers())->where(['id'=>$list_v['customers_id']])->value('customer_name');
            $list[$list_k]['preparation_name'] = (new User())->where(['id'=>$list_v['preparation_id']])->value('username');
            $list[$list_k]['examine_name'] = (new User())->where(['id'=>$list_v['examine_id']])->value('username');
            unset($list[$list_k]['preparation_id']);
            unset($list[$list_k]['examine_id']);

            $purchase_id = Db::name('kuyou_goods_saleexc')->where(['purchase_id'=>$list_v['id']])->column('exchange_id');
            $purchase = Db::name('kuyou_goods_sales_exchange')->where(['id'=>['in',$purchase_id]])->column('purchase_code');
            $list[$list_k]['returns_order_id'] = implode(',',$purchase);
        }
        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 销货订单生成销货单
     * @param string $purchase_code
     * @return array
     */
    public static function getPurchaseOrder($purchase_code){
        $last_customer = \think\Db::name('kuyou_sets')->where(['name'=>'customer'])->value('is_checked');
        $set_customer = '';
        if($last_customer){
            $set_customer = Db::name('kuyou_goods_sales')->order('id','DESC')->value('customers_id');
        }

        $row = (new SalesOrder())->where(['purchase_code'=>$purchase_code])->field('id,purchase_code,FROM_UNIXTIME(purchase_time,\'%Y-%m-%d\') as purchase_time,
            customers_id,preferential_rate,preferential_money,real_money,examine_status,note,pay_money,account,arrears,all_arrears,sale_user,receiving_address,account')->find();
        $address = Db::name('kuyou_customers')->where(['id'=>$set_customer])->value('getgoods_address');
        $last_read = \think\Db::name('kuyou_sets')->where(['name'=>'last_read'])->value('is_checked');
        $sale_user = '';
        if($last_read){
            $sale_user = Db::name('kuyou_goods_sales')->order('id','DESC')->value('sale_user');
        }

        $give_account = 0;$real_money = 0;$arrears = 0;$real_moneys = 0;
        if($row){
            $where = [];
            $where['purchase_code'] = $row['purchase_code'];
            $purchase_info = Db::name('kuyou_goods_sales_order_info')->alias('po')
                ->join('kuyou_goods g','g.goods_code=po.goods_code')
                ->join('kuyou_unit u','u.id=po.goods_unit')
                ->join('kuyou_stores s','s.id=po.stores_id')
                ->where($where)
                ->field("po.id,po.purchase_code,po.purchase_type,FROM_UNIXTIME(po.purchase_time,'%Y-%m-%d') as purchase_time,
            po.goods_code,g.goods_name,g.batch,g.serial,g.goods_image,g.shelf_life as guarantee,g.id as goods_id,
            po.goods_note,po.goods_attr,po.goods_unit,u.name as unit_name,po.stores_id,s.name as stores_name,po.allow_stock,po.number,po.default_unit,
            po.basic_nmber,po.unit_price,po.tax_included,po.discount,po.dis_money,po.all_money,po.tax_rate,po.tax_money,po.money_tax_price,po.preferential_money,po.remark")->select();

            foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                $purord_info = Db::name('kuyou_goods_saleord_info')->where(['order_id'=>$purchase_info_v['id']])->field('sum(number) as number,sum(money) as money')->select();
                $gp_number = isset($purord_info[0]['number'])?$purord_info[0]['number']:0;
                $real_money += isset($purord_info[0]['money'])?$purord_info[0]['money']:0;
                $real_moneys += $purchase_info_v['money_tax_price'];
                if($purchase_info_v['number']-$gp_number<=0){
                    unset($purchase_info[$purchase_info_k]);
                }else{
                    $unit = (new Goods())->getGoodsUnit($purchase_info_v['goods_id']);
                    if(isset($unit['unit_data'])){
                        foreach ($unit['unit_data'] as $unit_k=>$unit_v){
                            if($unit_v['id']==$purchase_info_v['goods_unit']){
                                $purchase_info[$purchase_info_k]['basic_nmber'] = ($purchase_info_v['number']-$gp_number)*$unit_v['advance_rate'];
                            }
                        }
                    }else{
                        $purchase_info[$purchase_info_k]['basic_nmber'] = ($purchase_info_v['basic_nmber']-$gp_number);
                    }
                    $purchase_info[$purchase_info_k]['all_money'] = ($purchase_info_v['number']-$gp_number)*$purchase_info_v['unit_price'];
                    $purchase_info[$purchase_info_k]['money_tax_price'] = ($purchase_info_v['number']-$gp_number)*$purchase_info_v['tax_included'];
                    $purchase_info[$purchase_info_k]['tax_money'] = ($purchase_info_v['number']-$gp_number)*$purchase_info_v['tax_money']/$purchase_info_v['number'];
                    $purchase_info[$purchase_info_k]['dis_money'] = $purchase_info[$purchase_info_k]['all_money']*($purchase_info_v['discount'])/100;
                    $arrears += $purchase_info[$purchase_info_k]['all_money'] -= $purchase_info[$purchase_info_k]['dis_money'];
                    $purchase_info[$purchase_info_k]['purchase_number'] = $purchase_info_v['number']-$gp_number;
                }

                $purchase_info[$purchase_info_k]['default_unit_name'] = (new Unit())->where(['id'=>$purchase_info_v['default_unit']])->value('name');

                $attribute_id = Db::name('kuyou_goods_attr')->where(['id'=>$purchase_info_v['goods_attr']])->value('attribute_id');
                $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$attribute_id])->value('attr_ids');
                $attribute_name = '';
                if($attribute_ids){
                    $attribute_ids = explode('&',$attribute_ids);
                    $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                    $attribute_name = implode('/',$attribute);
                }
                $purchase_info[$purchase_info_k]['attr_name'] = $attribute_name;
            }
            $give_account = Db::name('kuyou_customers')->where(['id'=>$row['customers_id']])->value('need_receive_account');
            //查询原始单据
            $enclosure_id = Db::name('kuyou_enclosure_log')->where(['order_id'=>$row['id'],'type'=>'4'])->column('enclosure_id');
            if(!empty($enclosure_id)){
                $row['enclosure_count'] = sizeof($enclosure_id);
                $row['enclosure_ids'] = implode(',',$enclosure_id);
                $row['enclosure_data'] = Db::name('kuyou_enclosure')->where(['id'=>['in',$enclosure_id]])->field('id,image')->select();
            }else{
                $row['enclosure_count'] = 0;
                $row['enclosure_ids'] = '';
                $row['enclosure_data'] = [];
            }
        }else{
            $row['customers_id'] = $set_customer;
            $row['receiving_address'] = $address;
            $row['sale_user'] = $sale_user;
            $row['account'] = 0;
            $row['customers_id'] = 0;
        }
        $row['sale_user_name'] = (new StaffMember())->where(['id'=>$row['sale_user']])->value('name');
        $row['account_name'] = (new Accounts())->where(['id'=>$row['account']])->value('account_name');
        $row['customers'] = (new Customers())->where(['id'=>$row['customers_id']])->value('customer_name');

        $row['real_money'] = $real_moneys;
        $purchase_info = isset($purchase_info)?$purchase_info:[];
        $give_account = $give_account+$real_money+$row['real_money'];
        $row['arrears'] = $real_moneys-$row['pay_money'];
        $row['all_arrears'] = $give_account;
        $row['info_list'] = $purchase_info;
        if(!empty($row)){
            return ['status'=>200,'msg'=>$row];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
    }

    /**
     * 获取详情
     * @param string $purchase_code
     * @return array
     */
    public static function getDetail($purchase_code){
        $detail = self::where(function ($query) use ($purchase_code) {
            $query->where('purchase_code', '=', $purchase_code);
        })->field("id,purchase_code,FROM_UNIXTIME(purchase_time,'%Y-%m-%d') as purchase_time,
            customers_id,preferential_rate,preferential_money,real_money,examine_status,note,pay_money,account,
            arrears,all_arrears,cost_data,pay_money,purchase_money as costs,customers_money,
            sale_user,receiving_address,account,examine_status")->find();
        if($detail){
            $detail['sale_user_name'] = (new StaffMember())->where(['id'=>$detail['sale_user']])->value('name');
            $detail['account_name'] = (new Accounts())->where(['id'=>$detail['account']])->value('account_name');

            $detail['customers'] = (new Customers())->where(['id'=>$detail['customers_id']])->value('customer_name');
            $where = [];
            $where['purchase_code'] = $detail['purchase_code'];
            $list = Db::name('kuyou_goods_sales_info')->alias('po')
                ->join('kuyou_goods g','g.goods_code=po.goods_code')
                ->join('kuyou_unit u','u.id=po.goods_unit')
                ->join('kuyou_stores s','s.id=po.stores_id')
                ->where($where)
                ->field("po.id,po.purchase_code,po.purchase_type,FROM_UNIXTIME(po.purchase_time,'%Y-%m-%d') as purchase_time,
            po.goods_code,g.goods_name,g.goods_image,po.goods_note,po.goods_attr,po.goods_unit,u.name as unit_name,po.stores_id,s.name as stores_name,po.allow_stock,po.number,po.default_unit,
             po.purchase_money,po.batch_id,po.batch_name,po.manufacture,po.guarantee,po.validity,g.batch,g.serial,
            po.basic_nmber,po.unit_price,po.tax_included,po.discount,po.dis_money,po.all_money,po.tax_rate,po.tax_money,po.money_tax_price,po.remark,po.sales_order_id,po.purchase_order_id")->select();
            foreach ($list as $list_k=>$list_v){

                if(!empty($list_v['manufacture'])){
                    $list[$list_k]['manufacture'] = date('Y-m-d',$list_v['manufacture']);
                }else{
                    $list[$list_k]['manufacture'] = '';
                }
                if(!empty($list_v['validity'])){
                    $list[$list_k]['validity'] = date('Y-m-d',$list_v['validity']);
                }else{
                    $list[$list_k]['validity'] = '';
                }
                $goods_serial = Db::name('kuyou_goods_serial')->where(['sale_id'=>$list_v['id']])->field('serial,remark')->select();
                $list[$list_k]['period'] = $goods_serial;

                $list[$list_k]['default_unit_name'] = (new Unit())->where(['id'=>$list_v['default_unit']])->value('name');

                $list[$list_k]['attr_name'] = '';
                if(!empty($list_v['goods_attr'])){
                    $attribute_id = Db::name('kuyou_goods_attr')->where(['id'=>$list_v['goods_attr']])->value('attribute_id');
                    $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$attribute_id])->value('attr_ids');
                    if($attribute_ids){
                        $attribute_ids = explode('&',$attribute_ids);
                        $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                        $list[$list_k]['attr_name'] = implode('/',$attribute);
                    }
                }
            }
            $detail['info_list'] = $list;

            //查询原始单据
            $enclosure_id = Db::name('kuyou_enclosure_log')->where(['order_id'=>$detail['id'],'type'=>'5'])->column('enclosure_id');
            if(!empty($enclosure_id)){
                $detail['enclosure_count'] = sizeof($enclosure_id);
                $detail['enclosure_ids'] = implode(',',$enclosure_id);
                $detail['enclosure_data'] = Db::name('kuyou_enclosure')->where(['id'=>['in',$enclosure_id]])->field('id,image')->select();
            }else{
                $detail['enclosure_count'] = 0;
                $detail['enclosure_ids'] = '';
                $detail['enclosure_data'] = [];
            }
        }
        if(!empty($detail)){
            if(!empty($detail['cost_data'])){
                $detail['cost_data'] = (array)json_decode($detail['cost_data'], true);
            }
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关数据'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'customers_id|客户'=>'require',
                'real_money|优惠后金额'=>'require|money',
                'info_list|详细销货信息'=>'require',
                'pay_money|本次付款'=>'money',
                'account|付款账户'=>'number',
                'arrears|本次欠款'=>'money',
                'all_arrears|总欠款'=>'money',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],11);//验证编号是否合法
                if($status){
                    $examine= (new Commons())->getSet('examine','is_checked');

                    $detail['info_list'] = (array)json_decode($detail['info_list'], true);

                    if($detail['pay_money']>0){
                        if(empty($detail['account'])){
                            return ['status'=>500,'msg'=>'请选择结算账户'];
                        }
                        $all_now_pay_money = $now_pay_money = trim($detail['pay_money']);
                    }else{
                        $all_now_pay_money = $now_pay_money = 0;
                    }

                    $customers = (new Customers())->where(['id'=>$detail['customers_id']])->field('id')->find();
                    if(empty($customers)){
                        return ['status'=>500,'msg'=>'客户不存在'];
                    }

                    if(isset($detail['sale_user']) && !empty($detail['sale_user'])){
                        $sale_user = (new StaffMember())->where(['id'=>$detail['sale_user']])->field('id')->find();
                        if(empty($sale_user)){
                            return ['status'=>500,'msg'=>'职员不存在'];
                        }
                    }

                    $serial= (new Sets())->where(['name'=>'serial'])->value('is_checked');
                    $batch= (new Sets())->where(['name'=>'batch'])->value('is_checked');

                    $data = [];
                    $number = 0;$all_money = 0;$purchase_order_id = '';$tax_money=0;$money_tax_price=0;
                    foreach ($detail['info_list'] as $k=>$v){
                        if(!empty($v['goods_code'])){//有产品编号
                            $number += (float)$v['number'];
                            $all_money += (float)$v['all_money'];
                            $tax_money += (float)$v['tax_money'];
                            $money_tax_price += (float)$v['money_tax_price'];

                            $order_info_id = null;
                            if(!empty($v['purchase_order_id'])){
                                $purchase_order_id = $v['purchase_order_id'];
                                $order_info_id = (new SalesOrderInfo())->where(['purchase_code'=>$purchase_order_id])->value('id');
                            }

                            if(!empty($v['purchase_order_id'])){
                                $purchase_order_id = $v['purchase_order_id'];
                            }

                            if(!isset($v['stores_id']) || empty($v['stores_id'])){
                                return ['status'=>500,'msg'=>'请选择仓库'];
                            }

                            unset($pay_money);unset($pay_status);
                            if($now_pay_money>0){
                                if($now_pay_money-$v['all_money']>=0){
                                    $pay_status = 1;
                                    $pay_money = $v['all_money'];
                                    $now_pay_money -= $pay_money;
                                }else{
                                    $pay_status = 2;
                                    $pay_money = $now_pay_money;
                                    $now_pay_money -= $now_pay_money;
                                }
                            }

                            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,serial,batch')->find();
                            $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$v['batch_id']])->find();

                            $goods_batch_info = [];
                            if($goods['batch']==1 && $batch==1){
                                if(empty($v['batch_name'])){
                                    return ['status'=>500,'msg'=>'请选择生产批次'];
                                }
                                if(empty($batch_data)){
                                    return ['status'=>500,'msg'=>'生产批次不存在'];
                                }
                                $goods_batch_info = [
                                    'batch_id'    => isset($batch_data['id'])?$batch_data['id']:'',
                                    'goods_id'    => $goods['id'],
                                    'goods_code'  => $v['goods_code'],
                                    'attribute_id'=> isset($v['goods_attr'])?$v['goods_attr']:0,
                                    'goods_unit'  => (int)$v['goods_unit'],
                                    'stores_id'   => $v['stores_id'],
                                    'stock'       => (float)$v['number'],
                                    'number'      => (float)$v['number'],
                                    'batch_name'  => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                                    'manufacture' => strtotime($v['manufacture']),
                                    'guarantee'   => $v['guarantee'],
                                    'validity'    => strtotime($v['validity']),
                                    'status'      => '0',
                                    'type'        => 2,
                                    'createtime'  => time(),
                                    'updatetime'  => time(),
                                ];
                            }

                            $serial_code = [];
                            if(isset($v['serial']) && $goods['serial']==1 && $serial==1){
                                if(empty($v['serial'])){
                                    return ['status'=>500,'msg'=>'请输入商品序列号'];
                                }
                                $period_period = $v['serial'];
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    $serial_code[] = $period_period_v['serial'];
                                }
                                $where = [];
                                $where['serial'] = ['in',$serial_code];
                                if(!empty($v['purchase_id'])){
                                    $where['purchase_code'] = $v['purchase_id'];
                                }
                                $goods_serial = Db::name('kuyou_goods_serial')->where($where)->column('serial');
                                if(empty($goods_serial)){
                                    return ['status'=>500,'msg'=>'商品序列号不存在'];
                                }
                                foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                    if(!in_array($serial_code_v,$goods_serial)){
                                        return ['status'=>500,'msg'=>$serial_code_v.'商品序列号不存在'];
                                    }
                                }
                                $goods_serials = Db::name('kuyou_goods_serial')->where(['status'=>['in',[2,3]],'serial'=>['in',$serial_code]])->column('serial');
                                if(!empty($goods_serials)){
                                    $goods_serials = implode(',',$goods_serials);
                                    return ['status'=>500,'msg'=>'商品序列号'.$goods_serials.'已经待出库，不可重复出库'];
                                }
                            }

                            $data[] = [
                                'purchase_code'     =>  $detail['purchase_code'],
                                'purchase_time'     =>  strtotime($detail['purchase_time']),
                                'customers_id'      =>  (int)$detail['customers_id'],//客户
                                'sale_user'         =>  isset($detail['sale_user'])?(int)$detail['sale_user']:null,//销售员
                                'receiving_address' =>  $detail['receiving_address'],

                                'goods_code'        =>  $v['goods_code'],//商品信息
                                'goods_note'        =>  $v['goods_note'],
                                'goods_unit'        =>  (float)$v['goods_unit'],

                                'stores_id'         =>  $v['stores_id'],
                                'allow_stock'       =>  (float)$v['allow_stock'],
                                'order_info_id'     =>  $order_info_id,
                                'number'            =>  (float)$v['number'],
                                'default_unit'      =>  (float)$v['default_unit'],
                                'basic_nmber'       =>  (float)$v['basic_nmber'],
                                'unit_price'        =>  (float)$v['unit_price'],
                                'discount'          =>  (float)$v['discount'],
                                'dis_money'         =>  (float)$v['dis_money'],
                                'all_money'         =>  (float)$v['all_money'],
                                'remark'            =>  $v['remark'],

                                'goods_attr'        =>  (float)$v['goods_attr'],
                                'tax_included'      =>  (float)$v['tax_included'],
                                'tax_rate'          =>  (float)$v['tax_rate'],
                                'tax_money'         =>  (float)$v['tax_money'],
                                'money_tax_price'   =>  (float)$v['money_tax_price'],

                                'batch_id'          => isset($batch_data['id'])?$batch_data['id']:'',
                                'batch_name'        => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                                'manufacture'       => strtotime($v['manufacture']),
                                'guarantee'         => $v['guarantee'],
                                'validity'          => strtotime($v['validity']),

                                'preferential_rate' =>  (float)$detail['preferential_rate'],
                                'preferential_money'=>  (float)$detail['preferential_money'],
                                'real_money'        =>  (float)$detail['real_money'],
                                'purchase_money'    =>  (float)$v['purchase_money'],
                                'preparation_id'    =>  $adminId,
                                'operation_id'      =>  $adminId,

                                'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                                'pay_money'         =>  isset($pay_money)?$pay_money:0,
                                'account'           =>  isset($pay_status)?$detail['account']:0,

                                'purchase_order_id' =>  $v['purchase_order_id'],

                                'createtime'        => time(),
                                'updatetime'        => time(),

                                'serial_code'       => $serial_code,
                                'goods_batch_info'  => $goods_batch_info
                            ];
                        }
                    }
                    if(!empty($data)){
                        if($all_now_pay_money>0){
                            if($all_now_pay_money-$all_money>=0){
                                $pay_status = 1;
                                $pay_money = $all_money;
                            }else{
                                $pay_status = 2;
                                $pay_money = $all_now_pay_money;
                            }
                        }

                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_time'     =>  strtotime($detail['purchase_time']),
                            'customers_id'      =>  (int)$detail['customers_id'],//客户
                            'sale_user'         =>  isset($detail['sale_user'])?(int)$detail['sale_user']:null,//销售员
                            'receiving_address' =>  $detail['receiving_address'],
                            'customers_money'   =>  (float)$detail['customers_money'],

                            'number'            =>  $number,
                            'all_money'         =>  $all_money,

                            'tax_money'         =>  $tax_money,//税
                            'money_tax_price'   =>  $money_tax_price,//价税合计

                            'preferential_rate' =>  (float)$detail['preferential_rate'],
                            'preferential_money'=>  (float)$detail['preferential_money'],
                            'real_money'        =>  (float)$detail['real_money'],
                            'purchase_money'    =>  (float)$detail['costs'],
                            'note'              =>  $detail['note'],
                            'preparation_id'    =>  $adminId,
                            'operation_id'      =>  $adminId,

                            'arrears'           =>  $detail['arrears'],
                            'all_arrears'       =>  $detail['all_arrears'],

                            'purchase_order_id' =>  $purchase_order_id,

                            'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                            'pay_money'         =>  isset($pay_money)?$pay_money:0,
                            'account'           =>  isset($pay_status)?$detail['account']:0,
                            'cost_data'         =>  isset($detail['cost_data'])?$detail['cost_data']:null,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    $model = new Sales();
                    $row = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                    if($row){
                        return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                    }
                    if($purchase_order_id){
                        $order_id = Db::name('kuyou_goods_sales_order')->where(['purchase_code'=>$purchase_order_id])->value('id');
                    }

                    //附件记录开始
                    $enclosureLog = [];
                    if(isset($detail['enclosure']) && !empty($detail['enclosure'])){//选择了原始单据
                        if(!empty($detail['enclosure'])){
                            $enclosure = explode(',',$detail['enclosure']);
                            $enclosurelist = Db::name('kuyou_enclosure')->where(['id'=>['in',$detail['enclosure']]])->select();
                            if(sizeof($enclosurelist)!=sizeof($enclosure)){
                                return ['status'=>500,'msg'=>'选择的原始单据有误，请重新选择'];
                            }else{
                                foreach ($enclosure as $k=>$v){
                                    $enclosureLog[] = [
                                        'enclosure_id'  => $v,
                                        'purchase_code' => $detail['purchase_code'],
                                        'type'          => '5',
                                    ];
                                }
                            }
                        }
                        unset($detail['enclosure']);
                    }
                    //附件记录结束

                    $info_id = Db::name('kuyou_goods_sales_order_info')->where(['purchase_code'=>$detail['purchase_code']])->column('id');
                    $result = false;
                    Db::startTrans();
                    try {
                        $model->allowField(true)->save($rowdata);
                        $result = $model->id;

                        //添加附件记录
                        if(!empty($enclosureLog)){
                            foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                                $enclosureLog[$enclosureLog_k]['order_id'] = $result;
                            }
                            Db::name('kuyou_enclosure_log')->insertAll($enclosureLog);
                        }
                        //添加附件记录结束

                        if(!empty($info_id)){
                            Db::name('kuyou_goods_saleord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
                        }
                        Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$detail['purchase_code']])->delete();
                        foreach ($data as $data_k=>$data_v){
                            $goods_serial = $data_v['serial_code'];
                            unset($data_v['serial_code']);

                            $goods_batch_info = $data_v['goods_batch_info'];
                            unset($data_v['goods_batch_info']);

                            $purchase_id = Db::name('kuyou_goods_sales_info')->insertGetId($data_v);

                            if($goods_batch_info){
                                $goods_batch_info['purchase_info_id'] = $purchase_id;
                                Db::name('kuyou_goods_batch_exchange_info')->insert($goods_batch_info);
                            }

                            //批次
                            if($goods_batch_info){
                                $goods_batch_info['purchase_info_id'] = $purchase_id;
                                Db::name('kuyou_goods_batch_sale_info')->insert($goods_batch_info);
                            }

                            if(!empty($goods_serial)){
                                Db::name('kuyou_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
                                    'status'=>'3',
                                    'sale_id' => $purchase_id,
                                    'sale_code' => $data_v['purchase_code']
                                ]);
                            }

                            if(!empty($data_v['order_info_id'])){
                                Db::name('kuyou_goods_saleord_info')->insert([
                                    'order_id'=>$data_v['order_info_id'],
                                    'purchase_id'=>$purchase_id,
                                    'number'=>$data_v['number'],
                                    'money'=>$data_v['pay_money'],
                                    'all_money'=>$data_v['all_money'],
                                    'tax_rate'=>$data_v['tax_rate'],
                                    'tax_money'=>$data_v['tax_money'],
                                    'money_tax_price'=>$data_v['money_tax_price']
                                ]);
                            }
                        }
                        if(!empty($purchase_order_id)){
                            if($result){
                                Db::name('kuyou_goods_saleord')->insert(['order_id'=>$order_id,'purchase_id'=>$result]);
                            }
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        return ['status'=>500,'msg'=>$e->getMessage()];
                    }
                    if($result){
                        if($examine!=1){
                            try {
                                $exa = self::examine($detail['purchase_code']);
                            } catch (Exception $e) {
                            }
                            if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                try {
                                    self::delDetail($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                return ['status'=>500,'msg'=>$exa['msg']];
                            }
                        }
                        return ['status'=>200,'msg'=>$detail['purchase_code']];
                    }else{
                        return ['status'=>500,'msg'=>'添加失败'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'old_purchase_code|原单据编号'=>'require',
                'purchase_code|单据编号'=>'require',
                'purchase_time|单据时间'=>'require',
                'customers_id|客户'=>'require',
                'real_money|优惠后金额'=>'require|money',
                'info_list|详细销货信息'=>'require',
                'pay_money|本次付款'=>'money',
                'account|付款账户'=>'number',
                'arrears|本次欠款'=>'money',
                'all_arrears|总欠款'=>'money',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $adminId = (new Commons())->getAdminId();
                if(empty($adminId)){
                    return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
                }
                $status = (new Commons())->checkCode($detail['purchase_code'],11);//验证编号是否合法
                if($status){
                    $model = new Sales();
                    $row = $model->where(['purchase_code'=>$detail['old_purchase_code']])->find();
                    if(empty($row)){
                        return ['status'=>500,'msg'=>'修改的单据不存在'];
                    }

                    $old_purchase_code = $detail['old_purchase_code'];

                    $examine= (new Commons())->getSet('examine','is_checked');

                    $detail['info_list'] = (array)json_decode($detail['info_list'], true);

                    $customers = (new Customers())->where(['id'=>$detail['customers_id']])->field('id')->find();
                    if(empty($customers)){
                        return ['status'=>500,'msg'=>'客户不存在'];
                    }

                    if(isset($detail['sale_user']) && !empty($detail['sale_user'])){
                        $sale_user = (new StaffMember())->where(['id'=>$detail['sale_user']])->field('id')->find();
                        if(empty($sale_user)){
                            return ['status'=>500,'msg'=>'职员不存在'];
                        }
                    }

                    if($detail['pay_money']>0){
                        if(empty($detail['account'])){
                            return ['status'=>500,'msg'=>'请选择结算账户'];
                        }
                        $all_now_pay_money = $now_pay_money = trim($detail['pay_money']);
                    }else{
                        $all_now_pay_money = $now_pay_money = 0;
                    }

                    $serial= (new Sets())->where(['name'=>'serial'])->value('is_checked');
                    $batch= (new Sets())->where(['name'=>'batch'])->value('is_checked');

                    $data = [];
                    $number = 0;$all_money = 0;$purchase_order_id = '';$tax_money=0;$money_tax_price=0;
                    foreach ($detail['info_list'] as $k=>$v){
                        if(!empty($v['goods_code'])){//有产品编号
                            $number += (float)$v['number'];
                            $all_money += (float)$v['all_money'];
                            $tax_money += (float)$v['tax_money'];
                            $money_tax_price += (float)$v['money_tax_price'];

                            $order_info_id = null;
                            if(!empty($v['purchase_order_id'])){
                                $purchase_order_id = $v['purchase_order_id'];
                                $order_info_id = (new SalesOrderInfo())->where(['purchase_code'=>$purchase_order_id])->value('id');
                            }

                            if(!empty($v['purchase_order_id'])){
                                $purchase_order_id = $v['purchase_order_id'];
                            }

                            if(!isset($v['stores_id']) || empty($v['stores_id'])){
                                return ['status'=>500,'msg'=>'请选择仓库'];
                            }

                            unset($pay_money);unset($pay_status);
                            if($now_pay_money>0){
                                if($now_pay_money-$v['all_money']>=0){
                                    $pay_status = 1;
                                    $pay_money = $v['all_money'];
                                    $now_pay_money -= $pay_money;
                                }else{
                                    $pay_status = 2;
                                    $pay_money = $now_pay_money;
                                    $now_pay_money -= $now_pay_money;
                                }
                            }

                            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,serial,batch')->find();
                            $batch_data = Db::name('kuyou_goods_batch')->where(['id'=>$v['batch_id']])->find();

                            $goods_batch_info = [];
                            if($goods['batch']==1 && $batch==1){
                                if(empty($v['batch_name'])){
                                    return ['status'=>500,'msg'=>'请选择生产批次'];
                                }
                                if(empty($batch_data)){
                                    return ['status'=>500,'msg'=>'生产批次不存在'];
                                }
                                $goods_batch_info = [
                                    'batch_id'    => isset($batch_data['id'])?$batch_data['id']:'',
                                    'goods_id'    => $goods['id'],
                                    'goods_code'  => $v['goods_code'],
                                    'attribute_id'=> isset($v['goods_attr'])?$v['goods_attr']:0,
                                    'goods_unit'  => (int)$v['goods_unit'],
                                    'stores_id'   => $v['stores_id'],
                                    'stock'       => (float)$v['number'],
                                    'number'      => (float)$v['number'],
                                    'batch_name'  => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                                    'manufacture' => strtotime($v['manufacture']),
                                    'guarantee'   => $v['guarantee'],
                                    'validity'    => strtotime($v['validity']),
                                    'status'      => '0',
                                    'type'        => 2,
                                    'createtime'  => time(),
                                    'updatetime'  => time(),
                                ];
                            }

                            $serial_code = [];
                            if(isset($v['serial']) && $goods['serial']==1 && $serial==1){
                                if(empty($v['serial'])){
                                    return ['status'=>500,'msg'=>'请输入商品序列号'];
                                }
                                $period_period = $v['serial'];
                                foreach ($period_period as $period_period_k=>$period_period_v){
                                    $serial_code[] = $period_period_v['serial'];
                                }
                                $where = [];
                                $where['serial'] = ['in',$serial_code];
                                if(!empty($v['purchase_id'])){
                                    $where['purchase_code'] = $v['purchase_id'];
                                }
                                $goods_serial = Db::name('kuyou_goods_serial')->where($where)->column('serial');
                                if(empty($goods_serial)){
                                    return ['status'=>500,'msg'=>'商品序列号不存在'];
                                }
                                foreach ($serial_code as $serial_code_k=>$serial_code_v){
                                    if(!in_array($serial_code_v,$goods_serial)){
                                        return ['status'=>500,'msg'=>$serial_code_v.'商品序列号不存在'];
                                    }
                                }
                                $goods_serials = Db::name('kuyou_goods_serial')->where(['status'=>['in',[2,3]],'serial'=>['in',$serial_code]])->column('serial');
                                if(!empty($goods_serials)){
                                    $goods_serials = implode(',',$goods_serials);
                                    return ['status'=>500,'msg'=>'商品序列号'.$goods_serials.'已经待出库，不可重复出库'];
                                }
                            }

                            $data[] = [
                                'purchase_code'     =>  $detail['purchase_code'],
                                'purchase_time'     =>  strtotime($detail['purchase_time']),
                                'customers_id'      =>  (int)$detail['customers_id'],//客户
                                'sale_user'         =>  isset($detail['sale_user'])?(int)$detail['sale_user']:null,//销售员
                                'receiving_address' =>  $detail['receiving_address'],

                                'goods_code'        =>  $v['goods_code'],//商品信息
                                'goods_note'        =>  $v['goods_note'],
                                'goods_unit'        =>  (float)$v['goods_unit'],

                                'stores_id'         =>  $v['stores_id'],
                                'allow_stock'       =>  (float)$v['allow_stock'],
                                'order_info_id'     =>  $order_info_id,
                                'number'            =>  (float)$v['number'],
                                'default_unit'      =>  (float)$v['default_unit'],
                                'basic_nmber'       =>  (float)$v['basic_nmber'],
                                'unit_price'        =>  (float)$v['unit_price'],
                                'discount'          =>  (float)$v['discount'],
                                'dis_money'         =>  (float)$v['dis_money'],
                                'all_money'         =>  (float)$v['all_money'],
                                'remark'            =>  $v['remark'],

                                'goods_attr'        =>  (float)$v['goods_attr'],
                                'tax_included'      =>  (float)$v['tax_included'],
                                'tax_rate'          =>  (float)$v['tax_rate'],
                                'tax_money'         =>  (float)$v['tax_money'],
                                'money_tax_price'   =>  (float)$v['money_tax_price'],

                                'batch_id'          => isset($batch_data['id'])?$batch_data['id']:'',
                                'batch_name'        => isset($batch_data['batch_name'])?$batch_data['batch_name']:'',
                                'manufacture'       => strtotime($v['manufacture']),
                                'guarantee'         => $v['guarantee'],
                                'validity'          => strtotime($v['validity']),

                                'preferential_rate' =>  (float)$detail['preferential_rate'],
                                'preferential_money'=>  (float)$detail['preferential_money'],
                                'real_money'        =>  (float)$detail['real_money'],
                                'purchase_money'    =>  (float)$v['purchase_money'],
                                'preparation_id'    =>  $adminId,
                                'operation_id'      =>  $adminId,

                                'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                                'pay_money'         =>  isset($pay_money)?$pay_money:0,
                                'account'           =>  isset($pay_status)?$detail['account']:0,

                                'purchase_order_id' =>  $v['purchase_order_id'],

                                'createtime'        => time(),
                                'updatetime'        => time(),

                                'serial_code'       => $serial_code,
                                'goods_batch_info'  => $goods_batch_info
                            ];
                        }
                    }
                    if(!empty($data)){
                        if($all_now_pay_money>0){
                            if($all_now_pay_money-$all_money>=0){
                                $pay_status = 1;
                                $pay_money = $all_money;
                            }else{
                                $pay_status = 2;
                                $pay_money = $all_now_pay_money;
                            }
                        }

                        $rowdata = [
                            'purchase_code'     =>  $detail['purchase_code'],
                            'purchase_time'     =>  strtotime($detail['purchase_time']),
                            'customers_id'      =>  (int)$detail['customers_id'],//客户
                            'sale_user'         =>  isset($detail['sale_user'])?(int)$detail['sale_user']:null,//销售员
                            'receiving_address' =>  $detail['receiving_address'],
                            'customers_money'   =>  (float)$detail['customers_money'],

                            'number'            =>  $number,
                            'all_money'         =>  $all_money,

                            'tax_money'         =>  $tax_money,//税
                            'money_tax_price'   =>  $money_tax_price,//价税合计

                            'preferential_rate' =>  (float)$detail['preferential_rate'],
                            'preferential_money'=>  (float)$detail['preferential_money'],
                            'real_money'        =>  (float)$detail['real_money'],
                            'purchase_money'    =>  (float)$detail['costs'],
                            'note'              =>  $detail['note'],
                            'preparation_id'    =>  $adminId,
                            'operation_id'      =>  $adminId,

                            'arrears'           =>  $detail['arrears'],
                            'all_arrears'       =>  $detail['all_arrears'],

                            'purchase_order_id' =>  $purchase_order_id,

                            'pay_status'        =>  isset($pay_status)?$pay_status:'0',
                            'pay_money'         =>  isset($pay_money)?$pay_money:0,
                            'account'           =>  isset($pay_status)?$detail['account']:0,
                            'cost_data'         =>  isset($detail['cost_data'])?$detail['cost_data']:null,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }

                    if($detail['purchase_code']!=$detail['old_purchase_code']){
                        $purchase_id = $model->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                        if($purchase_id){
                            return ['status'=>500,'msg'=>'单据编号已使用，请重新输入单据编号'];
                        }
                    }

                    if($purchase_order_id){
                        $order_id = Db::name('kuyou_goods_sales_order')->where(['purchase_code'=>$purchase_order_id])->value('id');
                    }

                    //附件记录开始
                    $enclosureLog = [];
                    if(isset($detail['enclosure']) && !empty($detail['enclosure'])){//选择了原始单据
                        if(!empty($detail['enclosure'])){
                            $enclosure = explode(',',$detail['enclosure']);
                            $enclosurelist = Db::name('kuyou_enclosure')->where(['id'=>['in',$detail['enclosure']]])->select();
                            if(sizeof($enclosurelist)!=sizeof($enclosure)){
                                return ['status'=>500,'msg'=>'选择的原始单据有误，请重新选择'];
                            }else{
                                foreach ($enclosure as $k=>$v){
                                    $enclosureLog[] = [
                                        'enclosure_id'  => $v,
                                        'purchase_code' => $detail['purchase_code'],
                                        'type'          => '5',
                                    ];
                                }
                            }
                        }
                        unset($detail['enclosure']);
                    }
                    //附件记录结束

                    $info_id = Db::name('kuyou_goods_sales_order_info')->where(['purchase_code'=>$detail['purchase_code']])->column('id');
                    if($row){
                        $res = false;
                        Db::startTrans();
                        try {
                            //关闭审核功能需先反审核一次已审核数据
                            if($examine!=1 && $row['examine_status']==1){
                                self::examinef($detail['old_purchase_code']);
                            }
                            //添加附件记录
                            Db::name('kuyou_enclosure_log')->where(['order_id'=>$row['id'],'type'=>'5'])->delete();
                            if(!empty($enclosureLog)){
                                foreach ($enclosureLog as $enclosureLog_k=>$enclosureLog_v){
                                    $enclosureLog[$enclosureLog_k]['order_id'] = $row['id'];
                                }
                                Db::name('kuyou_enclosure_log')->insertAll($enclosureLog);
                            }
                            //添加附件记录结束
                            $rowdata['updatetime'] = time();
                            $res = $model->where(['purchase_code'=>$detail['old_purchase_code']])->update($rowdata);
                            if(!empty($info_id)){
                                Db::name('kuyou_goods_saleord_info')->where(['purchase_id'=>['in',$info_id]])->delete();
                            }

                            $purchase_exchange_id = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$old_purchase_code])->column('id');
                            Db::name('kuyou_goods_serial')->where(['sale_id'=>['in',$purchase_exchange_id],'status'=>'3'])->update([
                                'status'=>'1',
                            ]);
                            Db::name('kuyou_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_exchange_id]])->delete();

                            Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$detail['purchase_code']])->delete();

                            foreach ($data as $data_k=>$data_v){
                                $goods_serial = $data_v['serial_code'];
                                unset($data_v['serial_code']);

                                $goods_batch_info = $data_v['goods_batch_info'];
                                unset($data_v['goods_batch_info']);

                                $purchase_id = Db::name('kuyou_goods_sales_info')->insertGetId($data_v);

                                //批次
                                if($goods_batch_info){
                                    $goods_batch_info['purchase_info_id'] = $purchase_id;
                                    Db::name('kuyou_goods_batch_sale_info')->insert($goods_batch_info);
                                }

                                if(!empty($goods_serial)){
                                    Db::name('kuyou_goods_serial')->where(['serial'=>['in',$goods_serial]])->update([
                                        'status'=>'3',
                                        'sale_id' => $purchase_id,
                                        'sale_code' => $data_v['purchase_code']
                                    ]);
                                }

                                if(!empty($data_v['order_info_id'])){
                                    Db::name('kuyou_goods_saleord_info')->insert([
                                        'order_id'=>$data_v['order_info_id'],
                                        'purchase_id'=>$purchase_id,
                                        'number'=>$data_v['number'],
                                        'money'=>$data_v['pay_money'],
                                        'all_money'=>$data_v['all_money'],
                                        'tax_rate'=>$data_v['tax_rate'],
                                        'tax_money'=>$data_v['tax_money'],
                                        'money_tax_price'=>$data_v['money_tax_price']
                                    ]);
                                }
                            }
                            Db::commit();
                        } catch (Exception $e) {
                            Db::rollback();
                            return ['status'=>500,'msg'=>$e->getMessage()];
                        }
                        if($res){
                            if($examine!=1){
                                try {
                                    $exa = self::examine($detail['purchase_code']);
                                } catch (Exception $e) {
                                }
                                if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                                    return ['status'=>500,'msg'=>$exa['msg']];
                                }
                            }
                            return ['status'=>200,'msg'=>'更新成功'];
                        }else{
                            return ['status'=>500,'msg'=>'更新失败'];
                        }
                    }else{
                        return ['status'=>500,'msg'=>'未查询到可更新数据'];
                    }
                }else{
                    return ['status'=>500,'msg'=>'编号规则错误'];
                }
            }
        }
    }

    /**
     * 删除
     * @param string $purchase_code
     * @return array
     */
    public static function delDetail($purchase_code){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $purchase_code = explode(',',$purchase_code);
            $model = new Sales();
            $examine= (new Commons())->getSet('examine','is_checked');

            $list = $model->where(['purchase_code'=>['in',$purchase_code]])->select();
            foreach ($list as $list_k=>$list_v){
                if($list_v['examine_status']==1 && $examine==1){
                    return ['status'=>500,'msg'=>'不能删除已审核的数据'];
                }
            }
            $goods_purchase_id = [];$goods_purchase_code = [];
            foreach ($list as $list_k=>$list_v){
                $purchase_id = Db::name('kuyou_collection_sale')->where(['purchase_number'=>$list_v['purchase_code']])->column('id');
                if(!empty($purchase_id)){
                    return ['status'=>500,'msg'=>'不能删除已生成收款单的数据'];
                }
                $purchase_id = Db::name('kuyou_goods_saleexc')->where(['purchase_id'=>$list_v['id'],'type'=>'2'])->column('exchange_id');
                if(!empty($purchase_id)){
                    return ['status'=>500,'msg'=>'不能删除已生成退货单的数据'];
                }
                if(!in_array($list_v['id'],$goods_purchase_id)){
                    $goods_purchase_id[] = $list_v['id'];
                }
                if(!in_array($list_v['purchase_code'],$goods_purchase_code)){
                    $goods_purchase_code[] = $list_v['purchase_code'];
                }
            }
            $goods_purchase_info = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>['in',$goods_purchase_code]])->column('id');

            $count = 0;
            $res = false;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    if ($v['examine_status']==1 && $examine!=1){
                        try {
                            self::examinef($v['purchase_code']);
                        } catch (Exception $e) {
                        }
                    }
                    $res = $model->where(['purchase_code'=>$v['purchase_code']])->delete();
                    $count += $res;
                    $exchange_info = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$v['purchase_code']])->column('id');
                    Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$v['purchase_code']])->delete();
                    Db::name('kuyou_goods_serial')->where(['sale_id'=>['in',$exchange_info]])->update(['status'=>'1']);
                    //删除附件记录
                    Db::name('kuyou_enclosure_log')->where(['order_id'=>$v['id'],'type'=>'5'])->delete();
                }
                Db::name('kuyou_goods_sales_summary')->where(['purchase_code'=>['in',$goods_purchase_code]])->delete();
                if(!empty($goods_purchase_id)){//销货订单关联
                    Db::name('kuyou_goods_saleord')->where(['purchase_id'=>['in',$goods_purchase_id]])->delete();
                    Db::name('kuyou_goods_batch_sale_info')->where(['purchase_id'=>['in',$goods_purchase_id]])->delete();
                }
                if(!empty($goods_purchase_info)){//销货订单详情关联
                    Db::name('kuyou_goods_saleord_info')->where(['purchase_id'=>['in',$goods_purchase_info]])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return ['status'=>500,'msg'=>$e->getMessage()];
            }
            if($res){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }
        $model = new Sales();
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }
        $set_discount = \think\Db::name('kuyou_sets')->where(['name'=>'discount'])->value('is_checked');

        $account_list_obj = Db::name('kuyou_accounts')->field('id,account_coding,account_name,balance')->select();
        $account_list = [];
        foreach ($account_list_obj as $account_list_obj_k=>$account_list_obj_v){
            $account_list[$account_list_obj_v['id']] = $account_list_obj_v;
        }
        $examine_ids = [];
        $accountData = [];
        $arrears = [];
        $log = [];
        $payment_log = [];$invoicing = [];
        foreach ($list as $list_k=>$list_v){
            $examine_ids[] = $list_v['id'];
            if($list_v['arrears']>0){
                $suppliers = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->field('id,need_receive_account')->find();
                if($suppliers){
                    $status = false;
                    foreach ($arrears as $arrears_k=>$arrears_v){
                        if($arrears_v['id']==$suppliers['id']){
                            $arrears[$arrears_k]['need_receive_account'] = $list_v['arrears']+$arrears_v['need_receive_account'];
                            $status = true;
                        }
                    }
                    if(!$status){
                        $arrears[] = [
                            'id'  => $suppliers['id'],
                            'need_receive_account'  => $list_v['arrears']+$suppliers['need_receive_account'],
                        ];
                    }
                }
            }
            if($list_v['pay_money']>0){
                $accountData[] = [
                    'balance'  => $list_v['pay_money'],
                    'account'  => $list_v['account'],
                ];
                if(!isset($account_list[$list_v['account']])){
                    return ['status'=>400,'msg'=>'请选择收款账户'];
                }
                $log[] = [
                    'account_coding'    => $account_list[$list_v['account']]['account_coding'],
                    'account_name'      => $account_list[$list_v['account']]['account_name'],
                    'balance'           => $account_list[$list_v['account']]['balance']-$list_v['pay_money'],
                    'income'            => $list_v['pay_money'],
                    'pay_time'          => time(),
                    'bill_code'         => $list_v['purchase_code'],
                    'business_type'     => 5,
                    'customers_id'      => $list_v['customers_id'],
                    'remark'            => $list_v['note'],
                    'createtime'        => time(),
                    'updatetime'        => time(),
                ];
            }
            $payment_log[] = [
                'customers_id'   => $list_v['customers_id'],
                'sale_user'      => $list_v['sale_user'],
                'business_type'  => 1,
                'bill_time'      => $list_v['purchase_time'],
                'bill_code'      => $list_v['purchase_code'],
                'bill_codes'     => $list_v['purchase_code'],
                'purchase_money' => $list_v['all_money'],
                'discount_money' => $list_v['preferential_money'],
                'real_money'     => $list_v['real_money'],
                'money_tax_price'=> $list_v['money_tax_price'],
                'pay_money'      => $list_v['pay_money'],
                'give_money'     => $list_v['arrears'],
                'reamrk'         => $list_v['note'],
                'createtime'     => time(),
            ];
            if($set_discount==1){
                $money = $list_v['real_money'];
            }else{
                $money = $list_v['money_tax_price'];
            }
            $invoicing[] = [
                'customers_id'   => $list_v['customers_id'],
                'status'         => $list_v['pay_status'],
                'bill_time'      => $list_v['purchase_time'],
                'bill_code'      => $list_v['purchase_code'],
                'bill_codes'     => $list_v['purchase_code'],
                'money'          => $list_v['real_money'],
                'tax'            => $list_v['tax_money'],
                'real_money'     => $money,
                'pay_money'      => 0,
                'give_money'     => $money,
                'createtime'     => time(),
            ];
        }
        $editstock = [];$addstock = [];$goods_stock = [];
        $info_list = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>['in',$purchase_code]])->select();

        $purchase_info_id = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>['in',$purchase_code]])->column('id');

        $purchase_info = [];
        $goods_stock_log = [];//收发详情
        $serial_log = [];//序列号跟踪
        foreach ($info_list as $list_k=>$list_v){
            //序列号跟踪
            $goods_serial = Db::name('kuyou_goods_serial')->where(['sale_id'=>$list_v['id']])->field('goods_id,serial,stores_id,attribute_id')->select();
            foreach ($goods_serial as $goods_serial_k=>$goods_serial_v){
                $serial_log[] = [
                    'goods_id'=>$goods_serial_v['goods_id'],
                    'stores_id'=>$goods_serial_v['stores_id'],
                    'attribute_id'=>$goods_serial_v['attribute_id'],
                    'serial'=>$goods_serial_v['serial'],
                    'business_type'=>'4',
                    'store_status'=>'2',
                    'remarks' => $list_v['remark'],
                    'purchase_id'=>$list_v['id'],
                    'customer_id'=>$list_v['customers_id'],
                    'purchase_code'=>$list_v['purchase_code'],
                    'purchase_time' => $list_v['purchase_time'],
                    'createtime'  => time(),
                    'updatetime'  => time(),
                ];
            }
            //序列号跟踪

            $info_list[$list_k]['sales_order_id']    = $list_v['id'];
            $info_list[$list_k]['createtime']        = time();
            $info_list[$list_k]['updatetime']        = time();
            $stock_number = $list_v['basic_nmber'];
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,unit_id')->find();
            $status = false;
            foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                if($goods_stock_v['id']==$goods['id']){
                    $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']-$stock_number;
                    $status = true;
                }
            }
            if(!$status){
                $goods_stock[] = [
                    'id'=>$goods['id'],
                    'inventory'=>$goods['inventory']-$stock_number,
                ];
            }
            //商品库存
            $where = [];
            $where['goods_code'] = $list_v['goods_code'];
            $where['stores_id'] = $list_v['stores_id'];
            if($list_v['goods_attr']>0){
                $goods_attr = $list_v['goods_attr'];
                if($goods_attr>0){
                    $where['attribute_id'] = $goods_attr;
                }
            }

            //获取成本单价
            $balance_cost=0;$balance_unit=0;
            $goods['goods_code'] = $list_v['goods_code'];
            $goods['store'] = $list_v['stores_id'];
            $goods['attr_id'] = $list_v['goods_attr'];
            $goodsInfo = (new Goods())->getGoodsInfo($goods);
            if(!isset($goodsInfo['msg']['price_data'][0]['purchase'])){
                return ['status'=>500,'msg'=>'商品信息获取错误'];
            }else{
                $balance_unit = $goodsInfo['msg']['price_data'][0]['purchase'];
            }
            //获取成本单价结束

            $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id')->find();
            if($stock){
                $status = false;
                foreach ($editstock as $editstock_k=>$editstock_v){
                    if($editstock_v['id']==$stock['id']){
                        $editstock[$editstock_k]['stock'] -= $stock_number;
                        $status = true;
                        $balance_cost   = (round($balance_unit*$stock_number,4));
                    }
                }
                if(!$status){
                    $editstock[] = [
                        'id'=>$stock['id'],
                        'stock'=>(round($stock['stock']-$stock_number,4))
                    ];
                    $balance_cost   = (round($balance_unit*$stock_number,4));
                }
            }else{
                $store = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                return ['status'=>500,'msg'=>'商品'.$store.'库存不足'];
            }
            $purchase_info[] = $list_v['id'];

            //收发详情
            if($goods){
                $goods_stock_log[] = [
                    'purchase_code' => $list_v['purchase_code'],
                    'purchase_id'   => $list_v['id'],
                    'purchase_time' => $list_v['purchase_time'],
                    'business_type' => '4',
                    'customer_id'   => $list_v['customers_id'],
                    'goods_id'      => $goods['id'],
                    'goods_code'    => $list_v['goods_code'],
                    'attribute_id'  => (float)$list_v['goods_attr'],
                    'goods_unit'    => (float)$list_v['goods_unit'],
                    'stores_id'     => (float)$list_v['stores_id'],
                    'remark'        => $list_v['remark'],
                    'out_number'    => (float)$list_v['number'],
                    'out_basics'    => (float)$list_v['basic_nmber'],
                    'out_unit'      => $balance_unit,
                    'out_cost'      => $balance_cost,
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ];
            }
            //收发详情结束
        }
        foreach ($editstock as $editstock_k=>$editstock_v){
            if($editstock_v['stock']<0){
                $store = Db::name('kuyou_stores')->where(['id'=>$list_v['stores_id']])->value('name');
                return ['status'=>500,'msg'=>$store.'库存不足,操作失败'];
            }
        }

        $order_count = [];
        $code_id = Db::name('kuyou_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->column('order_id');
        $purchase_order_info = Db::name('kuyou_goods_sales_order_info')
            
            ->field('id,purchase_code')
            ->where(['id'=>['in',$code_id]])
            ->select();
        foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
            $purord_info = Db::name('kuyou_goods_saleord_info')
                ->where(['order_id'=>$purchase_order_info_v['id'],'purchase_id'=>['in',$purchase_info]])->field('sum(number) as number,sum(money) as money,sum(all_money) as all_money')->find();
            $purchase_order_info[$purchase_order_info_k]['pay_count'] = isset($purord_info['number'])?$purord_info['number']:0;
            $purchase_order_info[$purchase_order_info_k]['pay_money'] = isset($purord_info['money'])?$purord_info['money']:0;
            $purchase_order_info[$purchase_order_info_k]['all_money'] = isset($purord_info['all_money'])?$purord_info['all_money']:0;
        }
        foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
            $status = false;
            foreach ($order_count as $order_count_k=>$order_count_v){
                if($order_count_v['purchase_code']==$purchase_order_info_v['purchase_code']){
                    $order_count[$order_count_k]['store_number'] += $purchase_order_info_v['pay_count'];
                    $status = true;
                }
            }
            if(!$status){
                $order_count[] = [
                    'purchase_code'  => $purchase_order_info_v['purchase_code'],
                    'store_number'  => $purchase_order_info_v['pay_count'],
                ];
            }
        }
        //修改状态
        if(!empty($order_count)){
            foreach ($order_count as $order_count_k=>$order_count_v){
                $number = Db::name('kuyou_goods_sales_order')->where(['purchase_code'=>$order_count_v['purchase_code']])->field('id,number,store_number')->find();
                if(($number['number']-$number['store_number'])<=$order_count_v['store_number']){
                    $order_count[$order_count_k]['status'] = 1;
                }else{
                    $order_count[$order_count_k]['status'] = 2;
                }
                $order_count[$order_count_k]['id'] = $number['id'];
            }
        }

        //批次库存数据
        //获取设置
        $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $number_decimal = $setList['number_decimal']['value'];
        $goods_serial = Db::name('kuyou_goods_sales_info')->where(['id'=>['in',$purchase_info_id]])->select();

        $goods_batch_add = [];$goods_batch_edit = [];$goods_batch_log = [];
        foreach ($goods_serial as $k=>$v){
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
            if($goods['batch']==1){
                //先通过单位计算需修改多单位商品的库存数量
                if($goods['unit_id']==$v['goods_unit']){
                    $stock_number = $v['number'];
                }else{
                    $unit_conversion = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']])->value('advance_rate');
                    if(empty($unit_conversion)){
                        return ['status'=>500,'msg'=>'商品单位信息查询失败'];
                    }else{
                        $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                    }
                }

                $where = [];
                $where['goods_id'] = $goods['id'];
                if($v['goods_attr']){
                    $where['attribute_id'] = $v['goods_attr'];
                }
                $where['stores_id'] = $v['stores_id'];
                $where['batch_id'] = $v['batch_id'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){
                    $status = false;
                    foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                        if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$v['goods_id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                            $goods_batch_add[$goods_batch_add_k]['stock'] -= $stock_number;
                            $status = true;
                        }
                    }
                    if(!$status){
                        $goods_batch_add[] = [
                            'batch_id' => $v['batch_id'],
                            'goods_id' => $goods['id'],
                            'goods_code' => $v['goods_code'],
                            'attribute_id' => $v['goods_attr'],
                            'stores_id' => $v['stores_id'],
                            'stock' => $stock_number,
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] -= $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']-$stock_number;
                    }
                }
                foreach ($goods_batch_edit as $k2=>$v2){
                    if($v2<0){
                        return ['status'=>500,'msg'=>'商品'.$goods['goods_name'].'库存不足'];
                    }
                }

                //商品批次跟踪
                $goods_batch_log[] = [
                    'goods_id'      => $goods['id'],
                    'goods_unit'    => $v['goods_unit'],
                    'stores_id'     => $v['stores_id'],
                    'batch_id'      => (float)$v['batch_id'],
                    'number'        => (float)$v['number'],
                    'purchase_code' => $v['purchase_code'],
                    'purchase_time' => $v['purchase_time'],
                    'business_type' => '4',
                    'remarks'       => $v['remark'],
                    'order_id'      => $v['id'],
                    'unit_price'    => $v['unit_price'],
                    'tax_included'  => $v['tax_included'],
                    'all_money'     => $v['all_money'],
                    'tax_money'     => $v['tax_money'],
                    'money_tax_price' => $v['money_tax_price'],
                    'customer_id'   => $v['customers_id'],
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ];
            }
            //商品批次跟踪结束
        }
        //批次库存数据结束

        //应收账款明细表
        $ex_list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0','arrears'=>['>','0']])->select();
        $accounts_receivable = [];
        foreach ($ex_list as $ex_list_k=>$ex_list_v){
            $accounts_receivable[] = [
                'customers_id'      => $ex_list_v['customers_id'],
                'purchase_time'     => $ex_list_v['purchase_time'],
                'purchase_code'     => $ex_list_v['purchase_code'],
                'business_type'     => '6',
                'receivable'        => $ex_list_v['arrears'],
                'staff_member_id'   => $ex_list_v['sale_user'],
                'remark'            => $ex_list_v['note'],
                'sale_money'        => $ex_list_v['money_tax_price'],
                'receivable_money'  => round(($ex_list_v['real_money']+$ex_list_v['customers_money']),4),
                'amount'            => $ex_list_v['preferential_money'],
                'cost'              => $ex_list_v['customers_money'],
                'real_money'        => $ex_list_v['pay_money'],
                'createtime'        => time(),
                'updatetime'        => time(),
            ];
        }

        //采购销售费用
        $cost_data = [];
        $suppliers = Db::name('kuyou_suppliers')->column('id','supplyer_code');
        foreach ($list as $list_k=>$list_v){
            if(!empty($list_v['cost_data'])){
                $cost_datas = (array)json_decode($list_v['cost_data'], true);
                foreach ($cost_datas as $cost_datas_k=>$cost_datas_v){
                    if(!empty($cost_datas_v['money'])){
                        $cost_data[] = [
                            'purchase_time'     => time(),
                            'purchase_code'     => (new Commons())->getCodes('',27),
                            'business_type'     => '2',
                            'suppliers_ids'     => $cost_datas_v['suppliers_id'],
                            'suppliers_id'      => $cost_datas_v['suppliers_id'],
                            'expend_type_id'    => $cost_datas_v['expend_type_id'],
                            'purchase_number'   => $list_v['purchase_code'],
                            'purchase_times'    => $list_v['purchase_time'],
                            'money'             => $cost_datas_v['money'],
                            'pay_money'         => $cost_datas_v['money'],
                            'remark'            => $cost_datas_v['remark'],
                            'preparation_id'    => $adminId,
                            'operation_id'      => $adminId,
                            'createtime'        => time(),
                            'updatetime'        => time(),
                        ];
                    }
                }
            }
        }

        //销售利润表
        $profit = [];
        foreach ($list as $list_k=>$list_v){
            $amount = null;
            $amounts = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$list_v['purchase_code']])->sum('dis_money');
            if($amounts>0){
                $amount = $amounts;
            }
            $profit[] = [
                'purchase_type' => '1',
                'purchase_code' => $list_v['purchase_code'],
                'purchase_time' => $list_v['purchase_time'],
                'customers_id'  => $list_v['customers_id'],
                'sale_user'     => $list_v['sale_user'],
                'preparation_id'=> $list_v['preparation_id'],
                'examine_id'    => $adminId,
                'number'        => $list_v['number'],
                'amount'        => $amount,
                'all_money'     => $list_v['all_money'],
                'tax_money'     => $list_v['tax_money'],
                'money_tax_price'=> $list_v['money_tax_price'],
                'preferential_money'=> $list_v['preferential_money'],
                'purchase_money'=> $list_v['purchase_money'],
                'real_money'    => $list_v['real_money'],
                'customers_money'=> $list_v['customers_money'],
                'need_money'    => $list_v['real_money']+$list_v['customers_money'],
                'pay_money'     => $list_v['pay_money'],
                'remark'        => $list_v['note'],
            ];
        }

        //核销单源单
        $writeoff_source = [];
        foreach ($list as $list_k=>$list_v){
            if($list_v['arrears']>0){
                $writeoff_source[] = [
                    'purchase_type' => 3,
                    'type' => 1,
                    'customers_id' => $list_v['customers_id'],
                    'purchase_code' => $list_v['purchase_code'],
                    'purchase_time' => $list_v['purchase_time'],
                    'price' => $list_v['real_money'],
                    'money' => $list_v['pay_money'],
                    'write_off' => $list_v['arrears'],
                    'remark' => $list_v['note'],
                ];
            }
        }

        Db::startTrans();
        try {
            if(!empty($writeoff_source)){
                Db::name('kuyou_writeoff_source')->insertAll($writeoff_source);
            }

            if(!empty($profit)){
                Db::name('kuyou_goods_sales_profit')->insertAll($profit);
            }
            if(!empty($cost_data)){
                Db::name('kuyou_cost')->insertAll($cost_data);
            }
            if(!empty($accounts_receivable)){
                Db::name('kuyou_accounts_receivable')->insertAll($accounts_receivable);
            }

            //序列号跟踪
            if(!empty($serial_log)){
                Db::name('kuyou_goods_serial_log')->insertAll($serial_log);
            }
            if(!empty($goods_stock_log)){
                Db::name('kuyou_goods_log')->insertAll($goods_stock_log);
            }
            //批次库存数据
            if(!empty($goods_batch_log)){
                Db::name('kuyou_goods_batch_log')->insertAll($goods_batch_log);
            }
            if(!empty($goods_batch_add)){
                Db::name('kuyou_goods_batch_stock')->insertAll($goods_batch_add);
            }
            if(!empty($goods_batch_edit)){
                foreach ($goods_batch_edit as $k=>$v){
                    Db::name('kuyou_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            //批次库存数据结束

            if(!empty($purchase_info_id)){
                Db::name('kuyou_goods_serial')->where(['sale_id'=>['in',$purchase_info_id]])->update(['store_status'=>'2']);
                Db::name('kuyou_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_info_id]])->update(['status'=>'1']);
            }
            if(!empty($order_count)){
                $goodsSalesOrder = (new SalesOrder());
                foreach ($order_count as $order_count_k=>$order_count_v){
                    $goodsSalesOrder->where(['id'=>$order_count_v['id']])->inc('store_number',$order_count_v['store_number'])->update();
                    unset($order_count[$order_count_k]['store_number']);
                }
                $goodsSalesOrder->saveAll($order_count);
            }
            if(!empty($payment_log)){
                (new SalesPaymentLog())->saveAll($payment_log);
            }
            if(!empty($invoicing)){
                 Db::name('kuyou_sales_invoicing')->insertAll($invoicing);
            }
            $result = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'0'])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>['in',$purchase_code]])->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            if(!empty($log)){
                Db::name('kuyou_accounts_log')->insertAll($log);
            }
            if(!empty($editstock)){
                (new GoodsStock())->saveAll($editstock);
            }
            if(!empty($goods_stock)){
                (new Goods())->saveAll($goods_stock);
            }
            if(!empty($arrears)){
                (new Customers())->saveAll($arrears);
            }
            Db::name('kuyou_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->update(['status'=>'1','times'=>time()]);
            Db::name('kuyou_goods_sales_summary')->insertAll($info_list);
            if(!empty($accountData)){
                foreach ($accountData as $accountData_k=>$accountData_v){
                    Db::name('kuyou_accounts')->where(['id'=>$accountData_v['account']])->inc('balance',$accountData_v['balance'])->update();
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        if(empty($adminId)){
            return ['status'=>410,'msg'=>'登陆无效，请重新登陆'];
        }

        $model = new Sales();
        $plist = $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->field('id,purchase_code,purchase_type,arrears,customers_id')->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要反审核的数据'];
        }
        foreach ($list as $list_k=>$list_v){
            $purchase_id = Db::name('kuyou_collection_sale')->where(['purchase_number'=>$list_v['purchase_code']])->column('id');
            if(!empty($purchase_id)){
                return ['status'=>500,'msg'=>'不能反审核已生成收款单的数据'];
            }
            $purchase_id = Db::name('kuyou_goods_saleexc')->where(['purchase_id'=>$list_v['id']])->column('exchange_id');
            if(!empty($purchase_id)){
                return ['status'=>500,'msg'=>'不能反审核已生成退货单的数据'];
            }
        }

        $arrears = [];
        foreach ($list as $list_k=>$list_v){
            if($list_v['arrears']>0){
                $suppliers = Db::name('kuyou_customers')->where(['id'=>$list_v['customers_id']])->field('id,need_receive_account')->find();
                if($suppliers){
                    $status = false;
                    foreach ($arrears as $arrears_k=>$arrears_v){
                        if($arrears_v['id']==$suppliers['id']){
                            $arrears[$arrears_k]['need_receive_account'] = $arrears_v['need_receive_account']-$list_v['arrears'];
                            $status = true;
                        }
                    }
                    if(!$status){
                        $arrears[] = [
                            'id'  => $suppliers['id'],
                            'need_receive_account'  => $suppliers['need_receive_account']-$list_v['arrears'],
                        ];
                    }
                }
            }
        }
        $list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->column('purchase_code');

        $account_list_obj = Db::name('kuyou_accounts')->field('id,account_coding,account_name,balance')->select();
        $account_list = [];
        foreach ($account_list_obj as $account_list_obj_k=>$account_list_obj_v){
            $account_list[$account_list_obj_v['id']] = $account_list_obj_v;
        }

        $log = Db::name('kuyou_accounts_log')->where(['bill_code'=>['in',$list],'business_type'=>5])->select();
        $accountData = [];
        foreach ($log as $list_k=>$list_v){
            $accountData[] = [
                'balance'  => $list_v['expenditure'],
                'account'  => $list_v['account_coding'],
            ];
        }

        $editstock = [];$goods_stock = [];
        $info_list = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>['in',$list]])->select();

        $purchase_info_id = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>['in',$list]])->column('id');

        $purchase_info = [];
        foreach ($info_list as $list_k=>$list_v){
            $info_list[$list_k]['createtime']        = time();
            $info_list[$list_k]['updatetime']        = time();
            $stock_number = $list_v['basic_nmber'];
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('id,attribute_id,inventory,goods_name')->find();
            $status = false;
            foreach ($goods_stock as $goods_stock_k=>$goods_stock_v){
                if($goods_stock_v['id']==$goods['id']){
                    $goods_stock[$goods_stock_k]['inventory'] = $goods_stock_v['inventory']+$stock_number;
                    $status = true;
                }
            }
            if(!$status){
                $goods_stock[] = [
                    'id'=>$goods['id'],
                    'inventory'=>$goods['inventory']+$stock_number,
                ];
            }
            //商品库存
            $where = [];
            $where['goods_code'] = $list_v['goods_code'];
            $where['stores_id'] = $list_v['stores_id'];
            if($list_v['goods_attr']>0){
                $goods_attr = $list_v['goods_attr'];
                if($goods_attr>0){
                    $where['attribute_id'] = $goods_attr;
                }
            }
            $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id')->find();
            if($stock){
                $status = false;
                foreach ($editstock as $editstock_k=>$editstock_v){
                    if($editstock_v['id']==$stock['id']){
                        $editstock[$editstock_k]['stock'] += $stock_number;
                        $status = true;
                    }
                }
                if(!$status){
                    $editstock[] = [
                        'id'=>$stock['id'],
                        'stock'=>(round($stock['stock']+$stock_number,2))
                    ];
                }
            }else{
                return ['status'=>500,'msg'=>'系统数据错误,反审核失败'];
            }
            $purchase_info[] = $list_v['id'];
        }

        $order_count = [];
        $code_id = Db::name('kuyou_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->column('order_id');
        $purchase_order_info = Db::name('kuyou_goods_sales_order_info')
            ->field('id,purchase_code')
            ->where(['id'=>['in',$code_id]])
            ->select();
        foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
            $purord_info = Db::name('kuyou_goods_saleord_info')
                ->where(['order_id'=>$purchase_order_info_v['id'],'purchase_id'=>['in',$purchase_info]])->field('sum(number) as number,sum(money) as money,sum(all_money) as all_money')->find();
            $purchase_order_info[$purchase_order_info_k]['pay_count'] = isset($purord_info['number'])?$purord_info['number']:0;
            $purchase_order_info[$purchase_order_info_k]['pay_money'] = isset($purord_info['money'])?$purord_info['money']:0;
            $purchase_order_info[$purchase_order_info_k]['all_money'] = isset($purord_info['all_money'])?$purord_info['all_money']:0;
        }
        foreach ($purchase_order_info as $purchase_order_info_k=>$purchase_order_info_v){
            $status = false;
            foreach ($order_count as $order_count_k=>$order_count_v){
                if($order_count_v['purchase_code']==$purchase_order_info_v['purchase_code']){
                    $order_count[$order_count_k]['store_number'] += $purchase_order_info_v['pay_count'];
                    $status = true;
                }
            }
            if(!$status){
                $order_count[] = [
                    'purchase_code'  => $purchase_order_info_v['purchase_code'],
                    'store_number'  => $purchase_order_info_v['pay_count'],
                ];
            }
        }
        //修改状态
        if(!empty($order_count)){
            foreach ($order_count as $order_count_k=>$order_count_v){
                $number = Db::name('kuyou_goods_sales_order')->where(['purchase_code'=>$order_count_v['purchase_code']])->field('id,number,store_number')->find();
                if($number['store_number']<=$order_count_v['store_number']){
                    $order_count[$order_count_k]['status'] = 0;
                }else{
                    $order_count[$order_count_k]['status'] = 2;
                }
                $order_count[$order_count_k]['id'] = $number['id'];
            }
        }

        //批次库存数据
        //获取设置
        $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $number_decimal = $setList['number_decimal']['value'];
        $goods_serial = Db::name('kuyou_goods_sales_info')->where(['id'=>['in',$purchase_info_id]])->select();

        $goods_batch_add = [];$goods_batch_edit = [];
        foreach ($goods_serial as $k=>$v){
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_name,attribute_id,inventory,unit_id,batch')->find();
            if($goods['batch']==1){
                //先通过单位计算需修改多单位商品的库存数量
                if($goods['unit_id']==$v['goods_unit']){
                    $stock_number = $v['number'];
                }else{
                    $unit_conversion = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$v['goods_unit']])->value('advance_rate');
                    if(empty($unit_conversion)){
                        return ['status'=>500,'msg'=>'商品单位信息查询失败'];
                    }else{
                        $stock_number = round(($v['number']*$unit_conversion),$number_decimal);
                    }
                }

                $where = [];
                $where['goods_id'] = $goods['id'];
                if($v['goods_attr']){
                    $where['attribute_id'] = $v['goods_attr'];
                }
                $where['stores_id'] = $v['stores_id'];
                $where['batch_id'] = $v['batch_id'];
                $goods_batch_stock = Db::name('kuyou_goods_batch_stock')->where($where)->find();
                if(empty($goods_batch_stock)){
                    $status = false;
                    foreach ($goods_batch_add as $goods_batch_add_k=>$goods_batch_add_v){
                        if($goods_batch_add_v['batch_id']==$v['batch_id'] && $goods_batch_add_v['goods_id']==$goods['id'] && $goods_batch_add_v['attribute_id']==$v['attribute_id'] && $goods_batch_add_v['stores_id']==$v['stores_id']){
                            $goods_batch_add[$goods_batch_add_k]['stock'] += $stock_number;
                            $status = true;
                        }
                    }
                    if(!$status){
                        $goods_batch_add[] = [
                            'batch_id' => $v['batch_id'],
                            'goods_id' => $goods['id'],
                            'goods_code' => $v['goods_code'],
                            'attribute_id' => $v['goods_attr'],
                            'stores_id' => $v['stores_id'],
                            'stock' => $stock_number,
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }else{
                    if(isset($goods_batch_edit[$goods_batch_stock['id']])){
                        $goods_batch_edit[$goods_batch_stock['id']] += $stock_number;
                    }else{
                        $goods_batch_edit[$goods_batch_stock['id']] = $goods_batch_stock['stock']+$stock_number;
                    }
                }
            }
        }
        //批次库存数据结束

        //应收账款明细表
        $ex_list = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->column('purchase_code');

        Db::startTrans();
        try {
            //销售利润表
            Db::name('kuyou_writeoff_source')->where(['purchase_code'=>['in',$list],'purchase_type'=>'3','type'=>'1'])->delete();

            foreach ($plist as $plist_k=>$plist_v){
                Db::name('kuyou_goods_sales_profit')->where(['purchase_type'=>'1','purchase_code'=>$list_v['purchase_code']])->delete();
            }
            Db::name('kuyou_cost')->where(['business_type'=>'2','purchase_number'=>['in',$ex_list]])->delete();
            Db::name('kuyou_accounts_receivable')->where(['business_type'=>'6','purchase_code'=>['in',$ex_list]])->delete();

            //序列号跟踪
            if(!empty($purchase_info_id)){
                Db::name('kuyou_goods_serial_log')->where(['business_type'=>'4','purchase_id'=>['in',$purchase_info_id]])->delete();
            }
            //收发详情
            if(!empty($purchase_info_id)){
                Db::name('kuyou_goods_log')->where(['business_type'=>'4','purchase_id'=>['in',$purchase_info_id]])->delete();
            }
            //批次库存数据
            //删除批次跟踪
            if(!empty($purchase_info_id)){
                Db::name('kuyou_goods_batch_log')->where(['business_type'=>'4','order_id'=>['in',$purchase_info_id]])->delete();
            }
            if(!empty($goods_batch_edit)){
                foreach ($goods_batch_edit as $k=>$v){
                    Db::name('kuyou_goods_batch_stock')->where(['id'=>$k])->update(['stock'=>$v]);
                }
            }
            //批次库存数据结束

            if(!empty($purchase_info_id)){
                Db::name('kuyou_goods_serial')->where(['sale_id'=>['in',$purchase_info_id]])->update(['store_status'=>'1']);
                Db::name('kuyou_goods_batch_sale_info')->where(['purchase_info_id'=>['in',$purchase_info_id]])->update(['status'=>'0']);
            }
            if(!empty($order_count)){
                $goodsSalesOrder = (new SalesOrder());
                foreach ($order_count as $order_count_k=>$order_count_v){
                    $goodsSalesOrder->where(['id'=>$order_count_v['id']])->dec('store_number',$order_count_v['store_number'])->update();
                    unset($order_count[$order_count_k]['store_number']);
                }
                $goodsSalesOrder->saveAll($order_count);
            }
            (new SalesPaymentLog())->where(['bill_codes'=>['in',$list]])->delete();
            (new SalesInvoicing())->where(['bill_codes'=>['in',$list]])->delete();

            $result = $model->where(['purchase_code'=>['in',$purchase_code],'examine_status'=>'1'])->update(['examine_status'=>0,'examine_id'=>0,'examine_time'=>'','operation_id'=>$adminId]);
            Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>['in',$list]])->update(['examine_status'=>'0','examine_id'=>0,'examine_time'=>'','operation_id'=>$adminId]);
            Db::name('kuyou_accounts_log')->where(['bill_code'=>['in',$list],'business_type'=>5])->delete();
            Db::name('kuyou_goods_sales_summary')->where(['purchase_code'=>['in',$list]])->delete();
            if(!empty($accountData)){
                foreach ($accountData as $accountData_k=>$accountData_v){
                    Db::name('kuyou_accounts')->where(['account_coding'=>$accountData_v['account']])->dec('balance',$accountData_v['balance'])->update();
                }
            }
            if(!empty($editstock)){
                (new GoodsStock())->saveAll($editstock);
            }
            if(!empty($goods_stock)){
                (new Goods())->saveAll($goods_stock);
            }
            if(!empty($arrears)){
                (new Customers())->saveAll($arrears);
            }
            Db::name('kuyou_goods_saleord_info')->where(['purchase_id'=>['in',$purchase_info]])->update(['status'=>'0']);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'反审核失败'];
        }
    }

    /**
     * 检测可生成退货单
     * @param string $purchase_code
     * @return array
     */
    public static function checkPurchase($purchase_code = null){
        if(empty($purchase_code)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $row = Db::name('kuyou_goods_sales')->where(['purchase_code'=>$purchase_code])
            ->field('examine_status,purchase_code')
            ->find();
        if(empty($row)){
            return ['status'=>500,'msg'=>'参数错误'];
        }
        $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
        if($examine==1){
            if($row['examine_status']!=1){
                return ['status'=>500,'msg'=>'此销货单未审核，不可生成退货单'];
            }
        }
        $purchase_info = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$row['purchase_code']])->select();
        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
            $purord_info = Db::name('kuyou_goods_saleexc_info')->where(['purchase_id'=>$purchase_info_v['id']])->field('sum(number) as number,sum(money) as money')->select();
            $gp_number = isset($purord_info[0]['number'])?$purord_info[0]['number']:0;
            if($purchase_info_v['number']-$gp_number<=0){
                unset($purchase_info[$purchase_info_k]);
            }
        }
        if(empty($purchase_info)){
            return ['status'=>500,'msg'=>'此销货单已全部生成退货单'];
        }
        return ['status'=>200,'msg'=>''];
    }
}
